package com.jmb.waimao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jmb.waimao.entity.EmailTask;
import com.jmb.waimao.service.EmailTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller for email task management
 */
@RestController
@RequestMapping("/api/email-tasks")
@Slf4j
public class EmailTaskController {

    @Autowired
    private EmailTaskService emailTaskService;

    /**
     * Create a new email task
     *
     * @param emailTask Email task to create
     * @return Created email task
     */
    @PostMapping
    public ResponseEntity<EmailTask> createTask(@RequestBody EmailTask emailTask) {
        EmailTask createdTask = emailTaskService.createTask(emailTask);
        return ResponseEntity.ok(createdTask);
    }

    /**
     * Execute an email task
     *
     * @param taskId Task ID
     * @return Execution result
     */
    @PostMapping("/{taskId}/execute")
    public ResponseEntity<Map<String, Object>> executeTask(@PathVariable Long taskId) {
        log.info("Executing email task: {}", taskId);

        // Start task execution asynchronously
        emailTaskService.executeTask(taskId);

        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("message", "Task execution started");
        result.put("taskId", taskId);

        return ResponseEntity.ok(result);
    }

    /**
     * Get task status
     *
     * @param taskId Task ID
     * @return Email task with current status
     */
    @GetMapping("/{taskId}")
    public ResponseEntity<EmailTask> getTaskStatus(@PathVariable Long taskId) {
        EmailTask task = emailTaskService.getTaskStatus(taskId);
        if (task != null && task.getDeleted() != 1) {
            return ResponseEntity.ok(task);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * Get all tasks with pagination
     *
     * @param page Page number
     * @param size Page size
     * @return Paged list of email tasks
     */
    @GetMapping
    public ResponseEntity<Page<EmailTask>> getAllTasks(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        Page<EmailTask> pageRequest = new Page<>(page, size);
        LambdaQueryWrapper<EmailTask> queryWrapper = new LambdaQueryWrapper<>();
        // Ensure we only return non-deleted tasks
        queryWrapper.eq(EmailTask::getDeleted, 0)
                    .orderByDesc(EmailTask::getCreateTime);

        Page<EmailTask> result = emailTaskService.page(pageRequest, queryWrapper);
        return ResponseEntity.ok(result);
    }

    /**
     * Delete a task
     *
     * @param taskId Task ID
     * @return Success message
     */
    @DeleteMapping("/{taskId}")
    public ResponseEntity<Map<String, Object>> deleteTask(@PathVariable Long taskId) {
        EmailTask task = emailTaskService.getById(taskId);
        if (task != null) {
            task.setDeleted(1);
            emailTaskService.updateById(task);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Task deleted successfully");

            return ResponseEntity.ok(result);
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "Task not found");

            return ResponseEntity.badRequest().body(result);
        }
    }
}
